package com.clkj.zhonghui.service.stored;

import com.clkj.zhonghui.dao.stored.*;
import com.clkj.zhonghui.dao.system.RuleMapper;
import com.clkj.zhonghui.dao.user.UserMapper;
import com.clkj.zhonghui.pojo.common.*;
import com.clkj.zhonghui.pojo.stored.*;
import com.clkj.zhonghui.pojo.system.Rule;
import com.clkj.zhonghui.pojo.user.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.util.*;

/**
 * @author yawang
 * @create 2024/07/15 11:02:42
 **/
@Service
public class StoredServiceImpl implements StoredService{
    @Autowired
    private UserStoredMapper userStoredMapper;
    @Autowired
    private StoredMapper storedMapper;
    @Autowired
    private RuleMapper ruleMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserStoredDetailMapper userStoredDetailMapper;
    @Autowired
    private StoredGradeMapper storedGradeMapper;
    @Autowired
    private ActivityLotteryMapper lotteryMapper;

    @Autowired
    private UserActMapper userActMapper;

    @Autowired
    private UserActDetailMapper userActDetailMapper;
    private Map map;
    @Override
    public Map listMain(Integer userId,Integer shopId) {
        Example example = new Example(UserStored.class);
        Example.Criteria criteria =  example.createCriteria();
        criteria.andEqualTo("userId",userId);
        UserStored userStored = userStoredMapper.selectOneByExample(example);
        if(userStored==null){
            userStored = new UserStored();
            userStored.setUserId(userId);
            userStored.setTotalStored(0.0);
            userStored.setShareMoney(0.0);
            userStored.setVipGrade(0);
            userStored.setResidueMoney(0.0);
            userStored.setShopId(shopId);
            userStoredMapper.insertSelective(userStored);
        }

        example = new Example(Stored.class);
        criteria =  example.createCriteria();
        criteria.andEqualTo("shopId",shopId).andEqualTo("storedFlag",0);
        List<Stored> storedList = storedMapper.selectByExample(example);

        example = new Example(Rule.class);
        criteria =  example.createCriteria();
        criteria.andEqualTo("shopId",shopId).andEqualTo("ruleFlag",0);
        Rule rule = ruleMapper.selectOneByExample(example);

        map = new HashMap();
        map.put("userStored",userStored);
        map.put("storedList", storedList);
        map.put("rule", rule);
        return map;
    }

    @Override
    public List<UserStoredDetail> listDetail(Integer userId,Integer flag) {
        Example example = new Example(UserStoredDetail.class);
        Example.Criteria criteria =  example.createCriteria();
        criteria.andEqualTo("userId",userId).andEqualTo("storedFlag",flag);
        return userStoredDetailMapper.selectByExample(example);
    }

    @Override
    public List<UserStoredDetail> listShareDetail(Integer userId) {
        Example example = new Example(UserStoredDetail.class);
        Example.Criteria criteria =  example.createCriteria();
        criteria.andEqualTo("shareId",userId).andEqualTo("storedFlag",0);
        return userStoredDetailMapper.selectByExample(example);
    }

    @Override
    public Map userPay(Integer userId,Integer shopId, Integer shareId, Double storedMoney, Double rebate, Double shareRebate, Integer flag, String openId,Integer ifDown, HttpServletRequest request) {
        SortedMap<String,Object> packageParams = new TreeMap();
        String orderNumber = DateFormatHelper.getCurTimestamp().toString();
        String redirect_url="https://www.ccclkj.cn:2040/stored/paySuccess";
        //处理业务
        String appId="";
        String appSecret="";
        String trade_type="";
        if(flag==1){
            //微信端支付
            appId = PayApi.wxAppId;
            appSecret =PayApi.wxAppSecret;
            trade_type="JSAPI";
        }else{
            appId = PayApi.AppId;
            appSecret =PayApi.AppSecret;
            trade_type="APP";
        }

        String partner = PayApi.partner;// appid
        String partnerKey = PayApi.partnerKey;

        String nonceStr = DateFormatHelper.getCurTimestamp().toString();
        String Ip = Util.getIpAddr(request);
        double realMoney = storedMoney*(100-rebate)/100l;
        double shareMoney= realMoney*0.1;



        Example example = new Example(UserStored.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId);
        UserStored userStored = userStoredMapper.selectOneByExample(example);
        if(userStored==null){
            userStored = new UserStored();
            userStored.setUserId(userId);
            userStored.setTotalStored(0.0);
            userStored.setShareMoney(0.0);
            userStored.setResidueMoney(0.0);
            userStored.setVipGrade(0);
            userStoredMapper.insertSelective(userStored);
        }

        double totals = userStored.getTotalStored()+storedMoney;
        StoredGrade  grade  = storedGradeMapper.listNum(totals);
        int num = userStored.getVipGrade();//我原来的党委
        if(grade!=null){
            if(grade.getVipNum()>userStored.getVipGrade()){
                num = grade.getVipNum();//我充值后的档位
            }
        }



        String totalFee = Util.getMoney(String.valueOf(realMoney));
        //userId + "@" + shareId + "@" + storedMoney--充值金额 +  "@" +shareMoney--上级的道德返利 +"@"+shopId+"@"+num--充值后我的等级+"@"+ifDown--是否绑定了上级;
        String attach =  userId + "@" + shareId + "@" + storedMoney +  "@" +shareMoney +"@"+shopId+"@"+num+"@"+ifDown;
        String mchId = partner;
        String body = "充值储值金";


        packageParams.put("appid",appId);
        packageParams.put("attach",attach);
        packageParams.put("body",body);
        packageParams.put("mch_id",mchId);
        packageParams.put("nonce_str", nonceStr);
        packageParams.put("notify_url",redirect_url);
        packageParams.put("out_trade_no",orderNumber);
        packageParams.put("spbill_create_ip", Ip);
        packageParams.put("total_fee",totalFee);
        packageParams.put("trade_type",trade_type);
        RequestHandler requestHandler = new RequestHandler(null,null);
        requestHandler.init(appId,appSecret ,partnerKey,partner);
        String sign = requestHandler.createSign(packageParams);
        System.out.println(sign);
        String xml = "<xml>" + "<appid>" + appId + "</appid>" + "<attach>"
                + attach + "</attach>" + "<body><![CDATA[" + body
                + "]]></body>" + "<mch_id>" + mchId + "</mch_id>"
                + "<nonce_str>" + nonceStr + "</nonce_str>" + "<notify_url>"
                + redirect_url + "</notify_url>" + "<out_trade_no>"
                + orderNumber + "</out_trade_no>" +
                "<spbill_create_ip>" + Ip + "</spbill_create_ip>"
                + "<sign>" + sign + "</sign>" + "<total_fee>" + totalFee
                + "</total_fee>" + "<trade_type>" + trade_type
                + "</trade_type>" ;
        if(flag==1){
            xml+=  "<openid>" + openId + "</openid>";
        }
        xml+= "</xml>";
        System.out.println(xml);
        String prePayId = "";
        String createdOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String result = PayUtil.httpRequest(createdOrderURL,"POST",xml);
        System.out.println(result);
        SortedMap<String,Object> finalpackage = new TreeMap();
        try {
            Map map = PayUtil.doXMLParse(result);
            String str = String.valueOf(System.currentTimeMillis()/1000);
            String returnCode = map.get("return_code").toString();
            if(returnCode.equals("SUCCESS")){
                prePayId = map.get("prepay_id").toString();

                finalpackage.put("appid",appId);
                finalpackage.put("timestamp",str);
                finalpackage.put("noncestr",nonceStr);
                String finalSign = requestHandler.createSign(finalpackage);
                if(flag==0){//app支付
                    finalpackage.put("package","Sign=WXPay");
                    finalpackage.put("partnerid",mchId);
                    finalpackage.put("prepayid",prePayId);
                    finalpackage.put("sign",finalSign);
                }else{//微信支付
                    finalpackage.put("package","prepay_id=" + prePayId);
                    finalpackage.put("signType", "MD5");
                    finalpackage.put("paySign", finalSign);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map = new HashMap();
        map.put("finalPackage",finalpackage);

        return map;

    }

    @Override
    public void paySuccess(HttpServletRequest request, HttpServletResponse response) {
        System.out.println( "回调进来了");
        String resXml = "";
        InputStream inStream;
        String attach="";
        try {
            inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
            Map m = PayUtil.parseXmlToList2(result);
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            if ("SUCCESS".equals(m.get("result_code").toString())) {
                resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml> ";

            } else {
                resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";

            }
            out.write(resXml.getBytes());
            out.flush();
            out.close();

            attach = m.get("attach").toString();
            String[] str = attach.split("@");
//userId + "@" + shareId + "@" + storedMoney--充值金额 +  "@" +shareMoney--上级的道德返利 +"@"+shopId+"@"+num--充值后我的等级+"@"+ifDown--是否绑定了上级;
            Integer userId = Integer.valueOf(str[0]);
            Integer parentId = Integer.valueOf(str[1]);
            Double storedNum = Double.valueOf(str[2]);//应充值2500
            Double sharePercent = Double.valueOf(str[3]);//给推荐人的金额
            Integer shopId = Integer.valueOf(str[4]);//实际支付2000
            Integer  grade = Integer.valueOf(str[5]);//充值后我的档位
            Integer  ifDown = Integer.valueOf(str[6]);//是否绑定上级

            if(ifDown==0){
                User user = new User();
                user.setUserId(userId);
                user.setIfDown(1);
                user.setShareId(parentId);
                userMapper.updateByPrimaryKeySelective(user);
            }

            UserStoredDetail  detail = new UserStoredDetail();
            detail.setUserId(userId);
            detail.setStoredMoney(storedNum);
            detail.setDateTime(DateFormatHelper.currentTimes());
            detail.setShareMoney(sharePercent);
            detail.setStoredFlag(0);
            userStoredDetailMapper.insertSelective(detail);
            userStoredMapper.updateUserStore(userId,storedNum,grade);
            if(parentId!=0&&parentId!=userId){//更新父级的分账账户金额
                userStoredMapper.updateParentStored(parentId,sharePercent,shopId);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void addStored(Stored stored) {
        storedMapper.insertSelective(stored);
    }

    @Override
    public List<Stored> listStored(Integer flag) {
        Example example = new Example(Stored.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("storedFlag",flag);
        return storedMapper.selectByExample(example);
    }

    @Override
    public void deleteStored(String ids) {
        Example example = new Example(Stored.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("storedId", Arrays.asList(ids.split(",")));
        storedMapper.deleteByExample(example);


    }

    @Override
    public Map listDrawMain(Integer shopId, Integer userId, Integer flag) {
        Example example = new Example(Stored.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("storedFlag",1);
        List<Stored> storedList = storedMapper.selectByExample(example);

        example = new Example(ActivitySharingRecord.class);
        criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId).andEqualTo("recordFlag",1).andEqualTo("recordChou",0);

        List<ActivitySharingRecord> activitySharingRecords = lotteryMapper.selectByExample(example);
        map = new HashMap();
        map.put("storedList", storedList);
        map.put("activitySharingRecords", activitySharingRecords);



        return map;
    }

    @Override
    public Map listActMain(Integer userId) throws ParseException {
        map = new HashMap();
        Example example = new Example(UserAct.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId);
        UserAct userAct = userActMapper.selectOneByExample(example);
        map.put("coupon",0);
        if(userAct==null){
            userAct = new UserAct();
            userAct.setUserId(userId);
            userAct.setCurrentDay(0);
            userAct.setDateTime(DateFormatHelper.currentTimes());
            userAct.setIsFirst(0);
            userAct.setIsCoupon(0);
            userActMapper.insertSelective(userAct);
        }else{
            //查看最后时间是否是本月
            Date start = DateFormatHelper.parseDate(userAct.getDateTime(),"yyyy-MM-dd");
            long num = DateFormatHelper.compareTo(start,new Date()).get("month");
            if(num>1){//不是本月
                userAct.setCurrentDay(0);
                userAct.setDateTime(DateFormatHelper.currentTimes());

            }
            if(userAct.getIsCoupon()==1){//有优惠券，看是否过期
                Date start1 = DateFormatHelper.parseDate(userAct.getInvaildTime(),"yyyy-MM-dd HH:mm:ss");
                long num1 = DateFormatHelper.timeDifference(start1,new Date()).get("hour");
                if(num1<=0){//过期
                    userAct.setIsCoupon(0);
                    userAct.setInvaildTime(null);
                    map.put("coupon",1);
                }
            }

            userActMapper.updateByExampleSelective(userAct,example);
        }
        example = new Example(UserActDetail.class);
        criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId).andCondition(" datediff(month,date_time,getDate()) = 0 ");
        List<UserActDetail> list = userActDetailMapper.selectByExample(example);


        map.put("act",userAct);
        map.put("detail", list);
        map.put("msg","act--用户活动的总天数，有没有优惠券，isCOupon==1表示有优惠券，0表示没有优惠券，优惠券过期日期的记录表；list--当月签到时间列表 coupon--1表示有优惠券，但是过期了，提醒用户 ");
        return map;
    }

    @Override
    public Map addActDetail(Integer userId, Integer dayNum) {
        UserActDetail detail = new UserActDetail();
        detail.setUserId(userId);
        detail.setDateTime(DateFormatHelper.currentTimes());
        userActDetailMapper.insertSelective(detail);
        map.put("isCoupon",0);
        if(dayNum==7){
            map.put("isCoupon",1);
        }

        return map;
    }

    @Override
    public Map addCoupon(Integer userId) throws ParseException {
        Example example = new Example(UserAct.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId);
        UserAct act = new UserAct();
        act.setIsCoupon(1);
        act.setInvaildTime(DateFormatHelper.getAddDay("date",7,"yyyy-MM-dd HH:mm:ss"));
        userActMapper.updateByExampleSelective(act,example);
        map.put("invaildTime", act.getInvaildTime());

        return map;
    }

    @Override
    public Map listUserImg(Integer userId, String picName, Integer shopId) throws IOException {
//        System.out.println(picName.substring(0,picName.length()-4));
        String name=picName.substring(0,picName.length()-4);
        String card="D:\\nginx-1.19.1\\html\\zhibanzhang\\resource\\zbz\\"+picName;

        String path = "D:\\nginx-1.19.1\\html\\zhibanzhang\\resource\\zbz\\";
        String imgPic = path+"share_"+userId+"_"+name+".png";//目标

        String pic="";//二维码
        String msg="";
        File file = new File(imgPic);
        if(!(file.exists() && file.isFile())){
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9cf9f21ba0cbf62b&redirect_uri=https://www.ccclkj.cn/sharePage/into.html&response_type=code&scope=snsapi_userinfo&state=0@"+shopId+"@"+userId+"@20#wechat_redirect" ;

            pic =path+ Util.creatPic(url, userId+"", path);
            msg = ImgUtils.graphicsGeneration(pic,card,imgPic);
        }else{
            msg = imgPic;
        }
        String shareImg = "https://www.ccclkj.cn/zhibanzhang/resource/zbz/"+"share_"+userId+"_"+name+".png";

        map = new HashMap();
        if(msg.equals("error")){
            map.put("flag", "error");
            return map;
        }else{
            map.put("flag", "success");
            map.put("url", shareImg);
            return map;
        }

    }

    @Override
    public PageInfo listAllUserStored(Integer page, Integer size, Integer userId) {
        PageHelper.startPage(page,size);

        return  new PageInfo(userStoredMapper.listAllUserStored(userId));
    }

    @Override
    public List<UserStoredDetail> listUserStoredDetail(Integer userId) {
        Example example = new Example(UserStoredDetail.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId).andNotEqualTo("detailType",1);
        return userStoredDetailMapper.selectByExample(example);
    }
}
